<?php
// 【最终完整版】m-merchant/do_change_password.php

header('Content-Type: application/json; charset=utf-8');

// --- 完整的Token验证逻辑 ---
function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%'; // !!重要!! 这个密钥必须和 login_handler.php 中的密钥完全一致
    if (!$token) return null;
    $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null;
    list($h, $p, $s) = $token_parts;
    $sig = base64_decode(str_replace(['-','_'],['+','/'], $s));
    $exp_sig = hash_hmac('sha256', $h.".".$p, $secret_key, true);
    if (!hash_equals($exp_sig, $sig)) return null;
    $payload = json_decode(base64_decode(str_replace(['-','_'],['+','/'], $p)), true);
    if ($payload === null || ($payload['exp']??0) < time()) return null;
    return $payload['data'];
}
function get_authorization_header() {
    if (isset($_SERVER['Authorization'])) return trim($_SERVER["Authorization"]);
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) return trim($_SERVER["HTTP_AUTHORIZATION"]);
    if (function_exists('getallheaders')) {
        $h = getallheaders(); if (isset($h['Authorization'])) return trim($h['Authorization']);
    } return null;
}
$user_data = verify_token(str_replace('Bearer ', '', get_authorization_header()));
if ($user_data === null) { http_response_code(401); echo json_encode(['status' => -99, 'msg' => '登录失效']); exit(); }


// --- 数据库操作 ---
include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");

$response = ['status' => -1, 'msg' => '无效的请求'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $proxy_acc_safe = mysqli_real_escape_string($con, $user_data['proxy_acc']);
    
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // 1. 后端数据校验
    if (empty($old_password) || empty($new_password) || empty($confirm_password)) {
        $response['msg'] = '所有密码项均为必填！';
        echo json_encode($response); exit;
    }
    if ($new_password !== $confirm_password) {
        $response['msg'] = '两次输入的新密码不一致！';
        echo json_encode($response); exit;
    }
    if (!preg_match('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/', $new_password)) {
        $response['msg'] = '新密码过于简单，请设置不低于8位的字母和数字组合。';
        echo json_encode($response); exit;
    }
    if ($old_password === $new_password) {
        $response['msg'] = '新密码不能与旧密码相同！';
        echo json_encode($response); exit;
    }

    // 2. 验证旧密码是否正确
    $sql_check = "SELECT proxy_pass FROM proxy WHERE proxy_acc = ?";
    $stmt_check = mysqli_prepare($con, $sql_check);
    mysqli_stmt_bind_param($stmt_check, "s", $proxy_acc_safe);
    mysqli_stmt_execute($stmt_check);
    $result_check = mysqli_stmt_get_result($stmt_check);
    $row_check = mysqli_fetch_assoc($result_check);
    
    if (!$row_check || $row_check['proxy_pass'] != $old_password) {
        $response['msg'] = '旧密码输入错误！';
        echo json_encode($response); exit;
    }
    mysqli_stmt_close($stmt_check);
    
    // 3. 验证通过，更新数据库
    $new_password_safe = mysqli_real_escape_string($con, $new_password);
    $sql_update = "UPDATE proxy SET proxy_pass = ? WHERE proxy_acc = ?";
    $stmt_update = mysqli_prepare($con, $sql_update);
    mysqli_stmt_bind_param($stmt_update, "ss", $new_password_safe, $proxy_acc_safe);
    
    if (mysqli_stmt_execute($stmt_update)) {
        $response = ['status' => 0, 'msg' => '密码修改成功！请使用新密码重新登录。'];
    } else {
        $response['msg'] = '数据库更新失败，请稍后重试。';
    }
    mysqli_stmt_close($stmt_update);
}

echo json_encode($response);
mysqli_close($con);
?>